<template>
  <view class="navigation">
    <eui-navbar ref="EuiNavBar" :title="c_id" :storeName="sysConfig.c_progress[origData.main.c_progress]" displayable="true" color="#000000" backgroundColor="#FFFFFF" />
    <view class="top-view">
<!--      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"-->
<!--                      @confirm="searchConfirm" @leftIconClick="scanCode" radius="30" :showFilter="false" />-->
    </view>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <eui-virtual-list refresher="true" :origList="origData.details" :isBottom="false" :showIndex="true" :showHeard="false" type="list"
      @lower="loadMore">
        <template v-slot:list="scope">
          <view class="item-view">
            <eui-text title="" :value="scope.c_gname" type="number2" :valueStyle="titleStyle" />
            <eui-text title="库存数量" :value="scope.c_n_inv" type="number2" :valueStyle="showRightStyle" />
            <eui-text title="编码" :value="scope.c_gcode" type="number2" />
            <eui-text title="初盘数量" :value="scope.c_n" type="number2" :valueStyle="showRightStyle" />
            <eui-text title="条码" :value="scope.c_barcode" type="number2" />
            <eui-text title="复盘数量" :value="scope.c_n2" type="number2" :valueStyle="showRightStyle" />
            <eui-text title="包装/单位" :value="scope.c_pack" :name="scope.c_unit" type="slash2" />
            <eui-text title="三盘数量" :value="scope.c_n3" type="number2" :valueStyle="showRightStyle" />
            <view style="width: 50%" />
            <eui-text title="终盘数量" :value="scope.c_n9" type="number2" :valueStyle="showRightStyle" />
          </view>
        </template>
      </eui-virtual-list>
    </view>
    <view class="bottom-view" v-if="Number(origData.main.c_progress) <= 3">
      <view class="center-style">
        <eui-button type="max2" :title="nextCountInput" singleTag="submit" @buttonClick="buttonClick"
                    v-if="c_id && !isLastInputStep" :disabled="disableNext"/>
        <view class="gap-view" />
        <eui-button type="max" :title="refreshCountInput" singleTag="confrim" @buttonClick="buttonClick"
                    v-if="c_id" :disabled="Number(origData.main.c_progress) == 0"/>
        <view class="gap-view" />
        <eui-button type="max" :title="refreshCountInputB" singleTag="confrimB" @buttonClick="buttonClick"
                    v-if="c_id && origData.main.c_mode2 == '3'" :disabled="Number(origData.main.c_progress) == 0"/>
      </view>
    </view>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">

    </eui-popup>
  </view>
</template>

<script setup type="ts">
import {onMounted, ref, reactive, computed} from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateStores, validateGds, defaultMapping, validateStoresAndWno  } from '@/hooks/useValidateMethod';
import { todayAdd, formatNow } from '@/hooks/useUtils';
import service from "@/common/service";
import {getRdsUrl, rdsRequest, rdsRequestAsync} from '@/hooks/rdsServices';
import { calcAtInByPt, validateOddLot, round, calcPtInByPtPay, calcPetpayByPtPay } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits, getDictList } from '../components/RelatedName.js';
import { init, getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import { validateAdnoLevel } from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";
import { getDcStoreInfo } from '@/hooks/useDcStoreInfo';
import {auditCount, auditCountInput, CountProgress} from "./app.js";

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300);
const titleStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis;font-size: 26rpx; font-weight: 600');
const showRightStyle = ref('text-align: right; font-weight: 500');

const searchText = ref('');
const c_id = ref(''); // 标题栏显示单号
const sUserStore = ref('');
const sUserStoreName = ref('');
const dataList = ref([]);
const origData = ref({
  main: {}, // 主表
  details: [], // 商品明显
});
const sysConfig = ref({
  c_progress: {}, // 盘点进度
  c_status: {}, // 单据状态
  c_input_mode: [], // 盘点录入方式
});
const currentGds = ref({}); // 当前新增的商品
const isScan = ref("是"); // 是否连续扫描模式
const inputMode = ref([]); // 1-数量、2-件数、3-件数+细数 (细数采用累计模式，大于含量时不覆盖件数)、4-见物扫物（逐个扫描商品条码，数量累加）
const isAutoAdd = ref("是"); //是否在连扫模式下商品数量自动+1
const defaultShelfNo = ref("无货架"); // 默认货架
const cursor = ref(0); // 件数+细数模式下，光标的位置

onMounted(() => {
  getListHeight()
})

const refreshCountInput = computed(() => {
  // 更新盘点数
  const {c_progress = '', c_mode2 = ''} = origData.value.main || {};
  let step = (CountProgress(c_mode2))[c_progress] || '盘点';
  return `更新${step}数`;
});

const refreshCountInputB = computed(() => {
  // 更新B盘点数
  const {c_progress = '', c_mode2 = ''} = origData.value.main || {};
  let step = (CountProgress(c_mode2))[Number(c_progress) + 1] || '盘点';
  return `更新${step}数`;
});

const nextCountInput = computed(() => {
  // 进入下一步盘点进度
  let step = '下一步';
  const {c_progress = '', c_mode2 = '', c_mode3} = origData.value.main || {};
  if (isLastInputStep.value) {
    step = '预审/确认';
  } else {
    const nextProgress = parseInt(c_progress, 10) + 1 + '';
    step = (CountProgress(c_mode2))[nextProgress];
  }
  return `开始${step}`;
});

const isLastInputStep = computed(() => {
  // 是否是最后盘次:
  // 1. @mode3 <> '0' AND @progress <> '3' OR
  // 2. @mode3 = '0' AND @mode2 NOT IN ('0', '3') AND @progress <> '2' OR
  // 3. @mode3 = '0' AND @mode2 IN ('0', '3') AND @progress <> '1'
  // c_mode2 复盘方式：0-无、1-全部复盘、2-差异复盘、3-AB盘点、4-抽样复盘'
  // c_mode3 三盘方式：0-无、1-全部三盘、2-差异三盘
  // c_progress 盘点进度：0-尚未开始、1-初盘、2-复盘、3-三盘、4-预审、5-确认、6-完成
  const {c_progress = '', c_mode2 = '', c_mode3} = origData.value.main || {};
  if (
      (c_mode3 != '0' && c_progress != '3') ||
      (c_mode3 === '0' && !['0', '3'].includes(c_mode2) && c_progress != '2') ||
      (c_mode3 === '0' && ['0', '3'].includes(c_mode2) && c_progress != '1')
  ) {
    return false;
  }
  return true;
});

const disableNext = computed(() => {
  // 是否禁用下一步按钮
  // 根据商品明细的第一行数据的当前盘次数量是否有更新（不为空）
  const {c_n, c_n2, c_n3} = origData.value.details[0] || {};
  // 当前盘次
  const {c_progress = ''} = origData.value.main || {};
  if (c_progress == '0') {
    return false;
  } else if (c_progress == '1' && c_n != null) {
    return false;
  } else if (c_progress == '2' && c_n2 != null) {
    return false;
  } else if (c_progress == '3' && c_n3 != null) {
    return false;
  }
  return true
});

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        listHeight.value = height / (res.windowWidth / 750) - 100;
      }).exec()
    }
  });
};

onLoad(async ({ c_id, c_gcode, c_store_id }) => {
  await getSysConfig();
  await getData(c_id);
})

// 录入列表的相同商品及货架的index
const sameGdsIndex = (item) => {
  return origData.value.details.findIndex(i => i.c_barcode == item.c_barcode);
}

const getSysConfig = async () => {
  (await getDictList("盘点进度")).forEach(item => sysConfig.value.c_progress[item.c_id] = item.c_name);
  (await getDictList("单据状态")).forEach(e => sysConfig.value.c_status[e.c_id] = e.c_name);
  (await getDictList("盘点录入方式")).forEach(e => sysConfig.value.c_input_mode.push({
    text: e.c_name,
    value: e.c_id,
  }));
}

const cacheDataList = ref([]);

const sizePage = 50;
const getData = async (searchId) => {
  // 根据单据id获取盘点单明细
  const objectData = {
    BillId: searchId,
  };
  service.enjoyShowLoading('正在加载...');
  const result = await rdsRequest(rdsUrl.scApi, '商品盘点单', 'EnjoyBillQuery', objectData);
  origData.value.main = result.ds[0];
  // 缓存所有数据
  cacheDataList.value = result.ds1;

  // 初始化显示前20条数据
  origData.value.details = cacheDataList.value.slice(0, sizePage);


  c_id.value = searchId;
  toggleMode(sysConfig.value.c_input_mode.filter(item => item.value == origData.value.main.c_input_mode));
  service.enjoyHideLoading();
}

 const loadMore = () => {
      const start = origData.value.details.length;
      const end = start + sizePage;
      const moreData = cacheDataList.value.slice(start, end);

      if (moreData.length > 0) {
        origData.value.details = [...origData.value.details, ...moreData];
      } else {
        // 没有更多数据
        uni.showToast({
          title: '没有更多数据了',
          icon: 'none'
        });
      }
    };

// 切换是否连续扫描模式
const toggleScan = (value) => {
  isScan.value = value;
}

// 切换录入方式
const toggleMode = (value) => {
  inputMode.value = value;
  if (value[0].value == '4') {
    isScan.value = '是';
  } else {
    isScan.value = '否';
  }
}

const searchConfirm = async (e) => {
  if (!e || !e.value) {
    return;
  }
}

// 扫码
const scanCode = (type) => {

}

const toggleAutoAdd = () => {
  isAutoAdd.value = value;
}

const buttonClick = async (t) => {
  const { loginInfo } = mainStore;
  let { singleTag } = t;
  switch (singleTag) {
    case 'confrim':
      confrim();
      break;
    case 'confrimB':
      confrimB();
      break;
    case 'submit':
      setCountStatus();// 复盘&三盘
      break;
  }
}

// 更新实盘数
const confrim = () => {
  auditCountInput({
    bill_id: c_id.value,
    oper_type: 'R',
    step: origData.value.main.c_progress,
    login_store_id: origData.value.main.c_store_id,
  }, () => {
    getData(c_id.value);
  });
}

// 更新B盘数
const confrimB = () => {
  auditCountInput({
    bill_id: c_id.value,
    oper_type: 'R',
    step: Number(origData.value.main.c_progress) + 1,
    login_store_id: origData.value.main.c_store_id,
  }, () => {
    getData(c_id.value);
  });
}

// 下一步盘点进度
const setCountStatus = () => {
  const { c_progress = '', c_mode2 = '' } = origData.value.main || {};
  const nextProgress = parseInt(c_progress, 10) + 1 + '';
  let step = (CountProgress(c_mode2))[nextProgress];
  auditCount({
    oper_type: 'P',
    bill_id: c_id.value,
    to_progress: nextProgress,
    is_clear: '0',
    min_sku_rate: '0',
    login_store_id: origData.value.main.c_store_id,
  }, () => {
    getData(c_id.value);
    // 路由到盘点列表，刷新
    uni.navigateTo({
      url: `./index`
    });
  });
}

// 预审&确认
const commitCountStatus = () => {
  const { c_progress = '', c_mode2 = '' } = origData.value.main || {};
  const nextProgress = parseInt(c_progress, 10) + 1 + '';
  let step = (CountProgress(c_mode2))[nextProgress];
  uni.showModal({
    title: '提示',
    content: `请确认预审或确认?`,
    cancelText: '预审',
    confirmText: '确认',
    success: async function (res) {
      if (res.confirm) {
        auditCount({
          oper_type: 'P',
          bill_id: c_id.value,
          to_progress: '5',
          is_clear: '0',
          min_sku_rate: '0',
          login_store_id: origData.value.main.c_store_id,
        }, () => {
          getData(c_id.value);
        });
      } else if (res.cancel) {
        auditCount({
          oper_type: 'P',
          bill_id: c_id.value,
          to_progress: '4',
          is_clear: '0',
          min_sku_rate: '0',
          login_store_id: origData.value.main.c_store_id,
        }, () => {
          getData(c_id.value);
        });
      }
    },
  });
}

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}
</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}
.top-view {
  width: 100%;
  height: 0rpx;
  background: #FFFFFF;
  margin-bottom: 20rpx;
}
.extra-view {
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: 100%;
}
.footer-view {
  width: 100%;
  flex: 1;
}
.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}
.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}
.gap-view {
  width: 20rpx;
  height: auto;
}
//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}
.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}
.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #ffffff;
}
.popup-bottom {
  background: #ffffff;
  border-top: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
}
</style>
